package com.dirox.confluence.labelmanagement.listener;

import com.opensymphony.xwork.config.ConfigurationManager;
import com.opensymphony.xwork.config.entities.ActionConfig;
import com.opensymphony.xwork.config.entities.ResultConfig;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Map;


public class LabelManagementListener implements InitializingBean,
    DisposableBean {
    private static final String ORIGINAL_VIEWLABEL_VM = "/labels/viewlabel.vm";
    private static final String OVERRIDE_VIEWLABEL_VM = "/templates/overridevm/viewlabel.vm";

    /**
     * This method overrides the default viewlabel.vm by our viewlabel.vm
     */
    @SuppressWarnings("unchecked")
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, ActionConfig> actionCfgMap = ConfigurationManager.getConfiguration()
                                                                     .getPackageConfig("labels")
                                                                     .getActionConfigs();
        Map<String, ResultConfig> resultMap = (Map<String, ResultConfig>) actionCfgMap.get(
                "viewlabel").getResults();
        resultMap.get("success").addParam("location", OVERRIDE_VIEWLABEL_VM);
        resultMap.get("input").addParam("location", OVERRIDE_VIEWLABEL_VM);
        resultMap.get("error").addParam("location", OVERRIDE_VIEWLABEL_VM);
        ConfigurationManager.getConfiguration().reload();
    }

    /**
     * This is called when the object is destroyed, and it set params back to
     * default viewlabel.vm
     */
    @SuppressWarnings("unchecked")
    @Override
    public void destroy() throws Exception {
        Map<String, ActionConfig> actionCfgMap = ConfigurationManager.getConfiguration()
                                                                     .getPackageConfig("labels")
                                                                     .getActionConfigs();
        Map<String, ResultConfig> resultMap = (Map<String, ResultConfig>) actionCfgMap.get(
                "viewlabel").getResults();
        resultMap.get("success").addParam("location", ORIGINAL_VIEWLABEL_VM);
        resultMap.get("input").addParam("location", ORIGINAL_VIEWLABEL_VM);
        resultMap.get("error").addParam("location", ORIGINAL_VIEWLABEL_VM);
        ConfigurationManager.getConfiguration().reload();
    }
}
